package cn.et.ceshi;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.TextFragment;
import org.apache.lucene.search.highlight.TokenSources;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.wltea.analyzer.lucene.IKAnalyzer;

import cn.et.ceshi.service.LuceService;
@RestController
public class IndexDemo {
	
	@Autowired
	LuceService ls;
	static String drc="E:\\index";
	//定义存储目录
	static Analyzer aly= new IKAnalyzer();
	//搜索
	@GetMapping("/solr")
	public List<Map> search(String foodname) throws Exception {
		Directory dr= FSDirectory.open(new File(drc));
		//读取存储目录
		DirectoryReader ird=DirectoryReader.open(dr);
		//搜索类
		IndexSearcher isearcher=new IndexSearcher(ird);
		//Lucene查询解析 用于指定查询的属性名和分词器
		QueryParser parser = new QueryParser(Version.LUCENE_47,"foodname", aly);
		//开始搜索
		Query query=parser.parse(foodname);
		//最终的结果被分词后添加前缀和后缀的处理类<B></B>
		SimpleHTMLFormatter htmlFormatter =new SimpleHTMLFormatter("<font color=red>","</font>");
		//将高亮搜索的词 添加到高亮处理器中
		Highlighter highlighter=new Highlighter(htmlFormatter,new QueryScorer(query));
		//获取搜索的结果指定返回的docuemnt个数
		ScoreDoc[] hits= isearcher.search(query, null, 10).scoreDocs;
		List<Map> list= new ArrayList<Map>();
		for(int i=0;i<hits.length;i++){
			//获取单独的document
			int id=hits[i].doc;
			Document hitDoc = isearcher.doc(hits[i].doc);
			Map map= new HashMap();
			map.put("foodid", hitDoc.get("foodid"));
			String foodname1 = hitDoc.get("foodname");
			//将查询的结果和搜索词匹配 匹配到添加前缀的后缀高亮
			TokenStream tokenStream=TokenSources.getAnyTokenStream(isearcher.getIndexReader(), id, "foodname", aly);
			//传入的第二个参数是查询到的值
			TextFragment [] frag=highlighter.getBestTextFragments(tokenStream, foodname1, false, 10);
			String foodnamehign=""; 	
				for(int j=0;j<frag.length;j++){
					if((frag[j]!=null)&&(frag[j].getScore()>0)){
						foodnamehign=frag[j].toString();
					}
				}
			map.put("foodname",foodnamehign);
			map.put("price", hitDoc.get("price"));
			map.put("imagepath", hitDoc.get("imagepath"));
			list.add(map);
			
		}
			ird.close();
			dr.close();
			return list;
			
	}
	
	//创建索引库
	@GetMapping("/writer")
	public String  write(){
		try{	
			//索引库的存储目录
			Directory dr= FSDirectory.open(new File(drc));
			//管联Lucene版本和当前分词器
			IndexWriterConfig cfi= new IndexWriterConfig(Version.LUCENE_47,aly);
			//传入目录和分词器
			IndexWriter iwriter = new IndexWriter(dr,cfi);
			//获取总数据的个数
			int queryCount=ls.queryFoodCount();
			int startIndex=0;
			int rows=14;
			//获取数据库里的数据
			while(startIndex<=queryCount){
				List<Map<String, Object>> lt= ls.query(startIndex,rows);
				for(Map f:lt){
					//document对象Field属性
					Document doc= new Document();
					//TextField.TYPE_STORED 写入存储目录
					Field field= new Field("foodid",f.get("foodid").toString(),TextField.TYPE_STORED);
					Field field1= new Field("foodname",f.get("foodname").toString(),TextField.TYPE_STORED);
					Field field2= new Field("price",f.get("price").toString(),TextField.TYPE_STORED);
					Field field3= new Field("imagepath",f.get("imagepath").toString(),TextField.TYPE_STORED);
					doc.add(field);
					doc.add(field1);
					doc.add(field2);
					doc.add(field3);
					//写入存储目录
					iwriter.addDocument(doc);
				}
				startIndex+=rows;
			}
			iwriter.commit();
			iwriter.close();
		}catch(Exception e){
			e.printStackTrace();
			return "0";
		}
		 return "1";
	}
}
